//
// Created by kriko on 2021/7/9.
//

#include <csapp.h>
#include <tcpcliserv/str_echo09.h>

void sig_child(int);

int main(int argc, char* argv[]) {
    int listenfd, connfd;
    pid_t childpid;
    socklen_t clienlen;
    sockaddr_storage clientaddr;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s <port>\n", argv[0]);
        return -1;
    }

    listenfd = Open_listenfd(atoi(argv[1]));
    Signal(SIGCHLD, sig_child);

    while(1) {
        clienlen = sizeof clientaddr;
        if ((connfd = Accept(listenfd, (SA*)&clientaddr, &clienlen)) < 0){
            if (errno == EINTR)
                continue;
            else
                unix_error("accept error");
        }
        if ((childpid = Fork()) == 0) {
            Close(listenfd);
            str_echo(connfd);
            return 0;
        }
        Close(connfd);
    }
}

void sig_child(int signo) {
    pid_t pid;
    int stat;

    while ((pid = waitpid(-1, &stat, WNOHANG)) > 0) {
        printf("child %d terminated\n", pid);
    }
    return;
}

